package com.wxt.blog.controller;

import com.wxt.blog.entity.User;
import com.wxt.blog.service.UserService;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/*")
public class UserController extends HttpServlet {
    private UserService userService = new UserService();

    // 重写doPost方法，处理HTTP POST请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getRequestURI().substring(request.getContextPath().length());

        // 判断路径是否为登录路径
        if ("/user/login".equals(path)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User user = userService.login(username, password);

            if (user != null) {
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }
        // 判断路径是否为注册路径
        else if ("/user/register".equals(path)) {
            // 获取表单数据：用户名、密码和邮箱
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");

            // 创建User对象并设置属性
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setEmail(email);

            // 调用Service的register方法进行用户注册
            boolean isSuccess = userService.register(newUser);

            // 处理注册结果
            if (isSuccess) {
                request.getSession().setAttribute("success", "注册成功，请登录");
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } else {
                request.setAttribute("error", "用户名已存在");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        }
    }

    // 重写doGet方法，处理HTTP GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getRequestURI().substring(request.getContextPath().length());

        // 判断路径是否为退出登录路径
        if ("/user/logout".equals(path)) {
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
    }
}